package com.example.demo.controller;

import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    //手动开启事务的两个对象
    @Resource
    private DataSourceTransactionManager transactionManager;
    @Resource
        private TransactionDefinition transactionDefinition;
    @RequestMapping("/add")
    public int add(UserInfo userInfo) {
        // todo : 非空校验
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
        || !StringUtils.hasLength(userInfo.getPassword())) {
            return 0;
        }
        userInfo.setCreatetime(LocalDateTime.parse(LocalDateTime.now().toString()));
        userInfo.setUpdatetime(LocalDateTime.parse(LocalDateTime.now().toString()));

        // 1. 开启事务
        TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);
        int res = userService.add(userInfo);
        System.out.println("添加：" + res);
        //2.回滚事务
       // transactionManager.rollback(transaction);
        //3.提交事务
        transactionManager.commit(transaction);
        return res;
    }

    @Transactional  //自动提交或回滚事务
    @RequestMapping("/insert")
    public Integer insert(UserInfo userInfo) {
        if (userInfo == null || !StringUtils.hasLength(userInfo.getUsername())
                || !StringUtils.hasLength(userInfo.getPassword())) {
            return 0;
        }
        userInfo.setCreatetime(LocalDateTime.parse(LocalDateTime.now().toString()));
        userInfo.setUpdatetime(LocalDateTime.parse(LocalDateTime.now().toString()));
        int res = userService.add(userInfo);
        int s = 10/0;
        System.out.println("添加：" + res);
        return 0;
    }

}
